package org.jeecg.modules.act.wx;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.wx.Encryption;
import org.jeecg.common.wx.WxUserInfo;
import org.jeecg.common.wx.tool;
import org.jeecg.modules.act.entity.ActUser;
import org.jeecg.modules.act.service.IActUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 微信小程序用户控制层
 */
@RestController
@RequestMapping("/wx/")
@Api(tags = "wx_小程序用户接口")
public class WxUserController {

    @Autowired
    private IActUserService actUserService;

    /**
     * @DESCRIPTION 获取openid
     * @params code
     * @DATE 2019-07-20 16:15
     **/
    @GetMapping("code")
    @ApiOperation(value = "小程序用户接口-获取openid", notes = "小程序用户接口-获取openid")
    public Result getOpenId(HttpServletRequest request) {
        Result<Map> result = new Result<>();
        String code = request.getParameter("code");
        String appId = request.getParameter("appId");
        String appSecret = request.getParameter("appSecret");
        String uAppId = Encryption.Base64Decode(appId);
        String uAppSecret = Encryption.Base64Decode(appSecret);
        Map map = WxUserInfo.info(code, uAppId, uAppSecret);
        if (StringUtils.isUndefined(map.get("openid"))) {
            result.setSuccess(false);
            result.setMessage("请重新获取openid");
        } else {
            result.setSuccess(true);
        }
        result.setResult(map);
        return result;
    }

    @PostMapping("loginByOpenId")
    @ApiOperation(value = "用户登录", notes = "登录")
    public Result<ActUser> loginByOpenId(String openId) {
        Result<ActUser> result = new Result<>();
        if (StringUtils.isUndefined(openId)) {
            result.setCode(1);
            result.setSuccess(false);
            result.setMessage("参数错误,未传入openid");
            result.setResult(null);
        } else {
            QueryWrapper<ActUser> wrapper = new QueryWrapper<>(new ActUser());
            wrapper.eq("openid", openId);
            ActUser user = actUserService.getOne(wrapper);
            if (user == null) {
                //注册小程序
                ActUser actUser = new ActUser();
                actUser.setOpenid(openId);
                actUser.setCreateTime(new Date());
                actUser.setType(1);
                actUser.setStatus(1);
                actUser.setDelFlag(0);
                actUser.setUpdateTime(new Date());
                actUserService.save(actUser);
                result.setResult(actUser);
            } else {
                //返回用户信息
                result.setResult(user);
            }
        }
        return result;
    }

    /**
     * @param session_key,encryptedData,iv
     * @DESCRIPTION 获取手机号
     * @DATE 2019-07-20 16:15
     **/
    @GetMapping("getPhone")
    @ApiOperation(value = "获取电话号码", notes = "获取电话号码")
    public Result<String> getPhoneNumber(String session_key, String encryptedData, String iv) {
        Result<String> result = new Result<>();
        String phone = tool.getPhoneNumber(encryptedData, session_key, iv);
        result.setResult(phone);
        return result;
    }

    /**
     * @param phone,openId
     * @DESCRIPTION 绑定用户信息
     * @DATE 2019-07-20 16:15
     **/
    @ApiOperation(value = "绑定用户电话", notes = "绑定用户电话")
    @PostMapping("bindByOpenId")
    public Result getUserInfoByPhone(String phone, String openId) {
        Result<ActUser> result = new Result<>();
        if (!checkPhone(phone, openId)) {
            result.setSuccess(false);
            result.setCode(1);
            result.setMessage("绑定失败,电话号码已被绑定");
            result.setResult(null);
        } else {
            QueryWrapper<ActUser> wrapper = new QueryWrapper<>(new ActUser());
            wrapper.eq("openid", openId);
            ActUser user = actUserService.getOne(wrapper);
            user.setPhone(phone);
            boolean b = actUserService.updateById(user);
            if (b) {
                //绑定用户信息
                result.setSuccess(true);
                result.setMessage("绑定成功");
                result.setResult(user);
            } else {
                result.setCode(1);
                result.setSuccess(false);
                result.setMessage("绑定失败");
                result.setResult(null);
            }
        }
        return result;
    }

    @PostMapping("updateInfo")
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    public Result<ActUser> updateInfo(@RequestBody ActUser user) {
        Result<ActUser> result = new Result<>();
        if (checkPhone(user.getPhone(), user.getOpenid())) {
            boolean b = actUserService.updateById(user);
            if (b) {
                result.setSuccess(true);
                result.setMessage("修改成功");
            } else {
                result.setCode(1);
                result.setSuccess(false);
                result.setMessage("修改失败");
            }
        } else {
            result.setSuccess(false);
            result.setCode(1);
            result.setMessage("绑定失败,电话号码已被绑定");
            result.setResult(null);
        }
        return result;
    }

    private boolean checkPhone(String phone, String openId) {
        QueryWrapper<ActUser> wrapper = new QueryWrapper<>(new ActUser());
        wrapper.ne("openid", openId);
        wrapper.eq("phone", phone);
        ActUser user = actUserService.getOne(wrapper);
        if (user == null) {
            return true;
        }
        return false;
    }
}
